<?php

/**
* IMDB scrapper
*/
class Buzz_IMDB
{
  private $urlSearch  = "http://akas.imdb.com/find?s=tt&q=%s";
  private $urlTitle   = "http://akas.imdb.com/title/%s/";
  
  private $regexList    = '#href="/title/(?P<id>tt\d+)/" [^>]+>(?P<title>[^<]+)</a>#';
  private $regexImg     = '#id="img_primary">(.*?)<img src="(?P<url>[^\"]+)"#s';
  private $regexAuthor  = '#href="/name/nm\d+/">(?P<author>.*?)<#';
  private $regexName    = '#<h1 class="header">(?P<name>.*?)<#s';
  private $regexDesc    = '#<p>.*?<p>(?P<desc>.*?)</p>.*?</p>#s';
  
  function __construct()
  {
  }
  
  private function get($url)
  {
    $curl = curl_init();
    $opt = array(
      CURLOPT_HEADER => false,
      CURLOPT_RETURNTRANSFER => 1,
      CURLOPT_CONNECTTIMEOUT => 3,
      CURLOPT_URL => $url
    );
    curl_setopt_array($curl, $opt);
    $page = curl_exec($curl);
    curl_close($curl);
    return $page;
  }
  
  private function scrapResultList($content)
  {
    preg_match_all($this->regexList, $content, $d);
    return (array_flip(array_unique(array_combine($d['title'], $d['id']))));
  }
  
  private function scrapResultInfo($content)
  {
    preg_match($this->regexImg, $content, $i);
    preg_match($this->regexName, $content, $n);
    preg_match($this->regexDesc, $content, $d);
    preg_match($this->regexAuthor, $content, $a);
    return array(
      'name'=>trim($n['name']),
      'author'=>trim($a['author']),
      'img'=> '/element/proxyimage?url='.rawurlencode($i['url']),
      'desc'=>html_entity_decode(strip_tags(trim($d['desc'])))
      );
  }
  
  public function search($title)
  {
    $encoded = rawurlencode($title);
    $url = sprintf($this->urlSearch, $encoded);
    $page = $this->get($url);
    return array_merge($this->scrapResultList($page), array('url'=> $url));
  }
  
  public function infoById($id)
  {
    $page = $this->get(sprintf($this->urlTitle, $id));
    return $this->scrapResultInfo($page);
  }
  
}

/*
$test = new Buzz_IMDB();
var_dump($test->search('dexter'));
var_dump($test->infoById('tt1282140'));
*/